#!/usr/bin/python

#Code for Internet enabled Raspberry Pi based switch located in the West Room of the Milwaukee Makerspace
#Reads state of pushbutton switches and send commands to arduino's IP address to turn lights on and off
#West Room consists of Zones 3, 6, 8, 9, and 10
#See https://code.google.com/p/mms-bms/wiki/ZoneReference for more information

import urllib
import RPi.GPIO as GPIO
import time

#Zone to Rpi Pin Mapping
zone_pin = {3:17,6:18,8:22,9:23,10:24}
#Initialize zone status - assume all lights are initially off
zone_status = {}
for i in zone_pin:
    zone_status[i] = False
#Set GPIO Pins to Input Mode
GPIO.setmode(GPIO.BCM)
for i in zone_pin:
    GPIO.setup(zone_pin[i],GPIO.IN)
    
#Zone-specific arduino commands to turn on lights
true_lookup = {1:"0",2:"1",3:"2",4:"3",5:"4",6:"5",7:"6",8:"7",9:"8",10:"9"}
#Zone-specific arduino commands to turn off lights
false_lookup = {1:"a",2:"b",3:"c",4:"d",5:"e",6:"f",7:"g",8:"h",9:"i",10:"j"}    
#arduino's IP address
arduino_ip = "http://192.168.1.64/?"

def arduino_command_lookup(current_zone,new_command):
    if new_command is True:
        return true_lookup[current_zone]
    else:
        return false_lookup[current_zone]
                
def sendCommand(current_zone,new_command):
    urllib.urlopen(arduino_ip + arduino_command_lookup(current_zone,new_command)) #send command to arduino
    print current_zone,new_command
    zone_status[current_zone] = new_command #update current status

def main():
    while True:
        for i in zone_pin:
            button_status = GPIO.input(zone_pin[i])
            if button_status is not zone_status[i]:  
                sendCommand(i,button_status)
            time.sleep(.02)

if __name__ == '__main__':
    main()           
            
